/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.view.crud.family;

import java.awt.Frame;
import java.util.Calendar;
import javax.swing.JDialog;
import systole.domain.clinicalInformation.Family;
import systole.exceptions.ExceptionDAO;
import systole.utils.ImageUtils;
import systole.view.crud.controller.ControllerEntityEdition;

/**
 *
 * @author jmj
 */
public class ControllerFamilyEdition extends ControllerEntityEdition {

    /**
     * 
     */
    public ControllerFamilyEdition() {
        super();
        this.entityName = "Familiar";
    }

    @Override
    protected void loadEntityOnForm() {
        Family familyToLoad = (Family) this.curretnEntity;
        JDialogFamily formToLoad = (JDialogFamily) this.editForm;
        formToLoad.getjEdtDescription().setText(familyToLoad.getName());
        formToLoad.getjCbmSex().setSelectedItem(familyToLoad.getSex());
    }

    @Override
    protected void loadEntityFromForm() {
        Family familyToLoad = (Family) this.curretnEntity;
        JDialogFamily formToLoad = (JDialogFamily) this.editForm;

        familyToLoad.setName(formToLoad.getjEdtDescription().getText());
        familyToLoad.setSex((String) formToLoad.getjCbmSex().getSelectedItem());
        familyToLoad.setLastUpdate(Calendar.getInstance());

    }

    @Override
    protected String valid() {
        JDialogFamily formToLoad = (JDialogFamily) this.editForm;
        Family family = (Family) this.curretnEntity;

        if ((formToLoad.getjEdtDescription().getText() == null) || (formToLoad.getjEdtDescription().getText().isEmpty())) {
            return "Debe ingresar la descripción";
        }

        try {
            if (this.facadeDB.getFamilyBroker().existFamily(formToLoad.getjEdtDescription().getText(), family.getId())) {
                return "Ya existe un familiar con la descripción ingresada";
            }
        } catch (ExceptionDAO ex) {
            this.facadeDB.refreshSession();
            return ex.getMessage();
        }

        if ((formToLoad.getjCbmSex().getSelectedItem() == null)) {
            return "Debe ingresar el sexo";
        }

        return null;
    }

    @Override
    protected void save() throws ExceptionDAO {
        if (this.isEditing()) {
            this.facadeDB.getFamilyBroker().update((Family) this.curretnEntity);
        } else {
            this.facadeDB.getFamilyBroker().insert((Family) this.curretnEntity);
        }
    }

    @Override
    protected void loadIconOnForm() {
        this.editForm.setIconImage(ImageUtils.buildImage("resources/icons/family/family16.png"));
    }

    @Override
    protected Object createEntity() {
        return new Family();
    }

    @Override
    protected JDialog createEditionForm(Frame parent) {
        return new JDialogFamily(parent, this);
    }
}
